﻿using HAF.FtpUtility.Enum;
using HAF.LogUtility;
using HAF.LogUtility.Assistantor;
using HAF.LogUtility.Except;
using System.Text.RegularExpressions;

namespace Iptv.ResourceDowner.Helper
{
    /// <summary>
    /// m3u8处理公有类
    /// </summary>
    public class M3u8Helper : PushMessageable
    {
        /// <summary>
        /// 获取m3u8文件
        /// </summary>
        /// <param name="m3u8fileUrl">本地m3u8文件地址</param>
        /// <param name="tsCount">m3u8中ts文件数量</param>
        public long GetM3u8Data(string m3u8fileUrl, out int tsCount)
        {
            long duration = 0L;
            tsCount = 0;

            WriteInfoMessageExt(LogOutName, "加载并解析本地M3U8文件{0}", m3u8fileUrl);
            string m3u8Content = FileAssistant.ReadAllText(m3u8fileUrl);
            if (!string.IsNullOrEmpty(m3u8Content))
            {
                //文件有效性判断
                if (m3u8Content.ToLower().StartsWith("#EXTM3U".ToLower()))
                {
                    foreach (string line in m3u8Content.Split('\n'))
                    {
                        //获取文件时长
                        if (line.Contains("#EXTINF:"))
                        {
                            string timeStr = Regex.Match(line, @"\d+").Value;
                            //string strTime = line.Substring(8, line.Length - 9);
                            //WriteDebugMessageExt(LogOutName, "timeStr {0} strTime {1}", timeStr, strTime);
                            double doubleDuration = double.Parse(timeStr);
                            duration += (long)doubleDuration;
                        }

                        if (line.Trim().ToLower().EndsWith(".TS".ToLower()))
                        {
                            tsCount++;
                        }
                    }

                    WriteDebugMessageExt(LogOutName, "M3U8文件{0} 中ts文件数量为{1} 时长为{2}", m3u8fileUrl, tsCount, DataTransfer.FormatTimeStr(duration * 1000));
                }
                else
                {
                    throw new RunException(TransferCode.FileCheckErr, "非标准M3U8文件格式");
                }
            }
            else
            {
                throw new RunException(TransferCode.FileCheckErr, "非标准M3U8文件格式");
            }
            return duration;
        }
    }
}
